<template>
  <div class="app-UploadImage">
    <div class="imgs" v-for="(item, index) in fileList" :key="index">
      <el-image :src="item.url" />
      <i class="el-icon-error" @click="handleDelete(index)"></i>
    </div>
    <el-upload
      :action="upload.action"
      :limit="limit"
      :accept="upload.accept"
      :file-list="fileList"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :http-request="httpRequest"
      :show-file-list="false"
      :auto-upload="true"
      list-type="picture-card"
      ref="upload">
      <i class="el-icon-plus" @click="submitUpload"></i>
    </el-upload>
  </div>
</template>
<script>
import { delImg } from '@/api/business/common'
export default {
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    fileList: {
      type: Array,
      default: () => []
    },
    attr: String,
  },
  data() {
    return {
      upload: {
        action: '',
        accept: '.jpg, .jpeg, .png'
      }
    }
  },
  methods: {
    submitUpload() {
      if (this.fileList.length <= 0) {
        return false
      }
      this.$refs.upload.submit()
    },
    handleUploadError(err) {
      this.$message({
        message: '上传失败, 请重试',
        type: 'error'
      })
    },
    handleExceed() {
      this.$message({
        message: `只允许上传${this.limit}个文件`,
        type: 'warning'
      })
    },
    httpRequest(param) {
      this.$emit('httpRequest', { param, attr: this.attr })
    },
    handleDelete(index) {
      this.$confirm('是否确认删除此张图片', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delImg(this.fileList[index].fileName)
      }).then(() => {
        this.$emit('delete', index, this.attr)
      }).catch(() => {})
    }
  }
}
</script>
<style lang="scss" scoped>
.app-UploadImage {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  .imgs {
    position: relative;

    i {
      color: red;
      font-size: 20px;
      position: absolute;
      top: 0;
      right: 15px;
      cursor: pointer;
    }
  }
  .el-image {
    width: 148px;
    height: 148px;
    margin: 0 15px 0 0;
  }
}
</style>